//
//  SEGDHBLEDoorManager.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/7/31.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGDHBLEDoorManager.h"
#import "DHBle.h"
#import "OneKeyApi.h"

@interface SEGDHBLEDoorManager ()<YYlockApiDelegate>
/**
 是否找到对应设备
 */
@property (nonatomic, assign) BOOL isFoundDevice;
/**
 是否开门完成
 */
@property (nonatomic, assign) BOOL isOpenDoorFinished;
/**
开门回调
*/
@property (nonatomic, copy) dispatch_block_t doorHandleCallback;

@end

@implementation SEGDHBLEDoorManager

//开门
- (void)openDoor {

    self.isFoundDevice = NO;
    self.isOpenDoorFinished = NO;
    [OneKeyApi shareInstance].delegate = self;
    
    //需要延迟来等待蓝牙初始化
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[OneKeyApi shareInstance] scanDeviceWithUUID:10.0f];
    });
    
    // 延迟10s处理门禁超时
    WeakSelf;
    self.doorHandleCallback = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
        [weakSelf seg_timeOutAction];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), self.doorHandleCallback);
}

#pragma mark-YYlockApiDelegate
//扫描设备回调
- (void)scanDeviceCallBack:(CBPeripheral *)peripheral RSSI:(int)level {
    if (self.isFoundDevice) return;

    DHBle * dhBleInstance = [DHBle shareInstance];
    NSString *deviceId = [dhBleInstance getDeviceIdForStringValue:peripheral];
    if([deviceId isEqualToString:self.doorModel.deviceid]) {
        self.isFoundDevice = YES;
        [[OneKeyApi shareInstance] oneKeyOpenDevice:peripheral andDevicePassword:self.doorModel.ssid];
        return;
    }
}
//扫描设备超时回调
- (void)scanDeviceEndCallBack {
    SEGLog(@"%s",__FUNCTION__);//方法回调多次 不准确
}
- (void)openCloseDeviceIICallBack:(DHBleResultType)result deviceBattery:(Byte)battery deviceId:(NSString *)devId {
    SEGLog(@"openCloseDeviceIICallBack: %ld ,battery: %hhu ,deviceId: %@ ",(long)result, battery, devId);
    
    switch (result) {
        case DHBLE_RESULT_OK://成功
        {
            [self seg_afterOpenDoorSuccess];
            break;
        }
        default://其他状态全部失败
        {
            // 处理两次失败回调的情况 第二次失败则不走回调
//            if (self.delegate && [self.delegate respondsToSelector:@selector(managerOpenDoorFailedWithMessage:)] && !self.isOpenDoorFinished) {
//                [self.delegate managerOpenDoorFailedWithMessage:kOpenDoorMessage_Failed];
//            }
            
            [self seg_timeOutAction];
        }
            break;
    }
    
    self.isOpenDoorFinished = YES;
    // 拿到确定的结果 就停止延迟回调的block
    if (self.doorHandleCallback) {
        dispatch_block_cancel(self.doorHandleCallback);
        self.doorHandleCallback = nil;
    }

}
- (void)disconnectDeviceCallBack {
    SEGLog(@"%s",__FUNCTION__);
}
#pragma mark - 私有方法
- (void)seg_afterOpenDoorSuccess {
    SEGLog(@"%s",__FUNCTION__);
//    if (self.delegate && [self.delegate respondsToSelector:@selector(managerOpenDoorSuccessWithShouldShowTips:)]) {
//        [self.delegate managerOpenDoorSuccessWithShouldShowTips:YES];
//    }
    
    if (self.delegateSubject) {
        [self.delegateSubject sendNext:nil];
        [self.delegateSubject sendCompleted];
    }
}
- (void)seg_timeOutAction {
    SEGLog(@"seg_timeOutAction");
//    if (!self.isOpenDoorFinished) {
//        if (self.delegate && [self.delegate respondsToSelector:@selector(managerOpenDoorFailedWithMessage:)]) {
//            [self.delegate managerOpenDoorFailedWithMessage:kOpenDoorMessage_Failed];
//        }
//    }
    
    if (self.delegateSubject && !self.isOpenDoorFinished) {
        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:SEGOpenDoorErrorType_OpenBluetoothDoorFail userInfo:@{NSLocalizedDescriptionKey:kOpenDoorMessage_Failed}];
        [self.delegateSubject sendError:error];
    }
}

@end
